
const RongIMLib = require('./libs/RongIMLib.miniprogram-1.0.8.js');
const RongIMEmoji = require('./libs/RongIMEmoji-2.2.6.js');

var params = {
    appKey: "x18ywvqfxc6nc"
};



App({
    onLaunch: function() {

        // wx.hideTabBar();

        var self = this;

        RongIMLib.RongIMClient.init('x18ywvqfxc6nc');
        // 连接状态监听器
        RongIMLib.RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {
                switch (status) {
                    case RongIMLib.ConnectionStatus.CONNECTED:
                        console.log('链接成功');
                        break;
                    case RongIMLib.ConnectionStatus.CONNECTING:
                        console.log('正在链接');
                        break;
                    case RongIMLib.ConnectionStatus.DISCONNECTED:
                        console.log('断开连接');
                        break;
                    case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                        console.log('其他设备登录');
                        break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                        console.log('域名不正确');
                        break;
                    case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                        console.log('网络不可用');
                        break;
                }
            }
        })

        // 消息监听器
        RongIMLib.RongIMClient.setOnReceiveMessageListener({
            // 接收到的消息
            onReceived: function (message) {
                // 判断消息类型
                switch (message.messageType) {
                    case RongIMLib.RongIMClient.MessageType.TextMessage:
                        // message.content.content => 文字内容
                        if (typeof self.globalData.writeInContent != 'undefined') { //在聊天页面才写入数据
                            self.globalData.writeInContent(1,message);//给接收者写入最新数据
                        }
                        break;
                    case RongIMLib.RongIMClient.MessageType.VoiceMessage:
                        // message.content.content => 格式为 AMR 的音频 base64
                        break;
                    case RongIMLib.RongIMClient.MessageType.ImageMessage:
                        // message.content.content => 图片缩略图 base64
                        // message.content.imageUri => 原图 URL
                        break;
                    case RongIMLib.RongIMClient.MessageType.LocationMessage:
                        // message.content.latiude => 纬度
                        // message.content.longitude => 经度
                        // message.content.content => 位置图片 base64
                        break;
                    case RongIMLib.RongIMClient.MessageType.RichContentMessage:
                        // message.content.content => 文本消息内容
                        // message.content.imageUri => 图片 base64
                        // message.content.url => 原图 URL
                        break;
                    case RongIMLib.RongIMClient.MessageType.InformationNotificationMessage:
                        // 提示条通知消息
                        if (typeof self.globalData.writeInNotification != 'undefined') {    //在聊天页面才写入数据
                            self.globalData.writeInNotification(1,message);                //给接收者写入最新数据
                        }
                        break;
                    case RongIMLib.RongIMClient.MessageType.ContactNotificationMessage:
                        // do something
                        break;
                    case RongIMLib.RongIMClient.MessageType.ProfileNotificationMessage:
                        if (typeof self.globalData.writeInMaterial != 'undefined') { //在聊天页面才写入数据
                            self.globalData.writeInMaterial(1, message);//给接收者写入最新数据
                        }
                        break;
                    case RongIMLib.RongIMClient.MessageType.CommandNotificationMessage:
                        // do something
                        break;
                    case RongIMLib.RongIMClient.MessageType.CommandMessage:
                        // do something
                        break;
                    case RongIMLib.RongIMClient.MessageType.UnknownMessage:
                        // do something
                        
                        if (message.objectName == "RM:TxtMsg") {
                            if (typeof self.globalData.writeInAuctionStatus != 'undefined') {   //在聊天页面才写入数据
                                self.globalData.writeInAuctionStatus(1, message);               //给接收者写入最新数据
                            }
                        }
                        if (message.objectName == "RM:Information"){
                            if (typeof self.globalData.writeSettlementMessage != 'undefined') {           //在聊天页面才写入数据
                                self.globalData.writeSettlementMessage(1, message);               //给接收者写入最新数据
                            }
                        }
                        break;
                    default:
                }
            }
        });
		wx.getStorage({
			key: 'user',
			success: function (res) {
				self.loginRonIMLib(res.data.r_token)
			},
			fail() {
				wx.login({
					success: res => {
						wx.request({
							url: self.url.requestUrl + '/login/login',
							method: 'POST',
							data: { code: res.code },
							success: function (data) {
								if (data.data.code == 1) {
									wx.setStorage({
										key: 'user',
										data: data.data.data
									})
									self.loginRonIMLib(data.data.data.r_token)
								}
							}
						})
					}
				})
			}
		})

        this.globalData.RongIMLib = RongIMLib;
    },
	loginRonIMLib(r_token){
		var self = this;
		// 用户登录融云**************************************
		RongIMLib.RongIMClient.connect(r_token, {
			onSuccess: function (userId) {
				console.log('Connect successfully. ' + userId);
				self.globalData.User_id = userId;
				var config = {
					size: 48, // 大小, 默认 24, 建议15 - 55
				};
				RongIMEmoji.init(config);
			},
			onTokenIncorrect: function () {
				console.log('token 无效');
			},
			onError: function (errorCode) {
				var info = '';
				switch (errorCode) {
					case RongIMLib.ErrorCode.TIMEOUT:
						info = '超时';
						break;
					case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
						info = '不可接受的协议版本';
						break;
					case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
						info = 'appkey不正确';
						break;
					case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
						info = '服务器不可用';
						break;
				}
			}
		});

		var callback = {
			onSuccess: function (userId) {
				console.log('Reconnect successfully. ' + userId);
			},
			onTokenIncorrect: function () {
				console.log('token无效');
			},
			onError: function (errorCode) {
				console.log(errorcode);
			}
		};
		var config = {
			// 默认 false, true 启用自动重连，启用则为必选参数
			auto: true,
			// 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
			url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
			// 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
			rate: [100, 1000, 3000, 6000, 10000]
		};
		RongIMLib.RongIMClient.reconnect(callback, config);
	},
    globalData: {
        userInfo: null,
        RongIMEmoji: RongIMEmoji,
        levelRule:[         // 计算规则
            { integral: 1000,  score:  1,  grade: 1, type: 'heart' },
            { integral: 3000,  score:  3,  grade: 2, type: 'heart' },
            { integral: 5000,  score:  5,  grade: 3, type: 'heart' },
            { integral: 10000, score:  10, grade: 4, type: 'heart' },
            { integral: 30000, score:  30, grade: 5, type: 'heart' },

            { integral: 50000,   score: 50,   grade: 1, type: 'diamond' },
            { integral: 100000,  score: 100,  grade: 2, type: 'diamond' },
            { integral: 300000,  score: 300,  grade: 3, type: 'diamond' },
            { integral: 500000,  score: 500,  grade: 4, type: 'diamond' },
            { integral: 1000000, score: 1000, grade: 5, type: 'diamond' },

            { integral: 3000000,  score: 3000,  grade: 1, type: 'crown' },
        ],
        // 计算方式
        levelRuleCount(score){
            for (var i = 0; i < this.levelRule.length;i++){
                if (this.levelRule[i].score >= score) {
                    return this.levelRule[i];
                    break;
                }
            }
        }
    },
    url: {
        requestUrl: "https://api.zhijsc.com" // 网络接口全局变量
    }
})